package com.bdqn.day1231.controller;

import com.bdqn.day1231.entity.User;
import com.bdqn.day1231.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author Cordy
 * @Date 2021-12-31
 * 此处为UI层,是Spring MVC的控制器,实现前后端交互
 */
@Controller
public class UserController {
    @Resource
    private UserService userService;

    //请求的地址: http://localhost:5080/test
    @RequestMapping("/test")
    @ResponseBody//返回一个json字符串{'name':'tom','age':19}
    public String test(String username, String password) {
        String info = userService.getUserByNameAndPass(username, password);
        //返回逻辑视图,也就一个网页
        return info;
    }

    ///////////////以下为用户登录注册操作/////////////////
//    1.1跳转到登录页
    @RequestMapping("/")
    public String goLogin() {
        return "pages/login";
    }

    //   1.2执行登录
    @RequestMapping("/dolog")
    public String doLogin(String username, String password, Map map) {
        String info = userService.getUserByNameAndPass(username, password);
        if ("ok".equals(info)) {
            //切换到成功页
            map.put("username", username);
            return "pages/success";
        } else {
            //将错误信息传给前端网页
            map.put("error", info);
            return "pages/login";
        }
    }

    //2.1跳转到注册页面
    @RequestMapping("/goreg")
    public String goReg() {
        return "pages/register";
    }

    //2.2执行注册
    @RequestMapping("/doreg")
    public String doReg(User user, Map map) {
        String info = userService.saveUser(user);
        map.put("info", info);
        return "pages/register";
    }
}
